from datetime import datetime

from django.db import models, transaction


class SubscriptionManager(models.Manager):
    def get_queryset(self):
        return super(SubscriptionManager, self).get_queryset().filter(
            is_enabled=True, owner__is_enabled=True)


class Subscription(models.Model):
    """
    公众号基本信息

    """
    name = models.CharField(
        '名称', max_length=20, db_index=True)
    owner = models.ForeignKey(
        'User', models.CASCADE, 'owned_subscriptions', verbose_name='所有者')
    is_enabled = models.BooleanField(
        '是否有效', default=True)
    create_time = models.DateTimeField(
        '创建时间', default=datetime.now, db_index=True)
    update_time = models.DateTimeField(
        '更新时间', auto_now=True, db_index=True)

    enabled = SubscriptionManager()

    class Meta:
        db_table = 'subscription'

    @classmethod
    def create(cls, user, name, **kwargs):
        """
        建立公众号模型与其他相关模型

        :param name: 公众号名称
        :param kwargs: 其他公众号模型相关的关键字参数

        """
        with transaction.atomic():
            subscription = cls(owner=user, name=name, **kwargs)
            subscription.save()
        return subscription


class SubscriptionFollowerManager(models.Manager):
    def get_queryset(self):
        return super(SubscriptionFollowerManager, self).get_queryset().filter(
            subscription__is_enabled=True, follower__is_enabled=True)


class SubscriptionFollower(models.Model):
    """
    公众号关注者记录

    """
    subscription = models.ForeignKey(
        'Subscription', models.CASCADE, 'follower_records', verbose_name='公众号')
    follower = models.ForeignKey(
        'User', models.CASCADE, 'subscriptions', verbose_name='关注者')

    create_time = models.DateTimeField(
        '加入时间', default=datetime.now)

    enabled = SubscriptionFollowerManager()

    class Meta:
        db_table = 'subscription_follower'
        
    @classmethod
    def exist(cls, user, subscription):
        """
        检查user是否关注了公众号

        """
        return cls.enabled.filter(follower=user, subscription=subscription).exists()
